<template>
	<baseDialog ref="dialogRef" :title="dialogTitle" width="680px" @confirm="handleSubmit" @close="handleClose">
		<el-form ref="formRef" :model="formData" label-width="97px" :rules="rules">
			<el-form-item label="名称：" prop="name">
				<div class="w-80">
					<el-input v-model="formData.name" placeholder="请输入任务名称" maxlength="30" clearable />
				</div>
			</el-form-item>
			<el-form-item label="命令：" prop="command">
				<div class="w-80">
					<el-input v-model="formData.command" placeholder="请输入命令，例如：version" clearable />
				</div>
			</el-form-item>
			<el-form-item label="运行规则：" required>
				<el-row :gutter="12">
					<el-col :span="6">
						<el-select v-model="formData.expression.type" @change="getExpressionLists">
							<el-option v-for="item in typeList" :key="item.value" :value="item.value" :label="item.name"></el-option>
						</el-select>
					</el-col>
					<el-col v-if="formData.expression.type == 6" :span="6">
						<el-select v-model="formData.expression.week" @change="getExpressionLists">
							<el-option v-for="item in weekList" :key="item.value" v-bind="item"></el-option>
						</el-select>
					</el-col>
					<el-col v-if="[2, 7].includes(formData.expression.type)" :span="6">
						<div class="input-number-wrapper">
							<el-input
								:controls="false"
								v-model="formData.expression.day"
								:max="formData.expression.type === 2 ? 10000 : 31"
								:min="1"
								@blur="getExpressionLists"
							></el-input>
							<span class="suffix">{{ formData.expression.type === 2 ? '天' : '日' }}</span>
						</div>
					</el-col>
					<el-col v-if="[1, 2, 4, 6, 7].includes(formData.expression.type)" :span="6">
						<div class="input-number-wrapper">
							<el-input controls-position="right" v-model="formData.expression.hour" :max="23" :min="0" @blur="getExpressionLists"></el-input>
							<span class="suffix">时</span>
						</div>
					</el-col>
					<el-col v-if="[1, 2, 3, 4, 5, 6, 7].includes(formData.expression.type)" :span="6">
						<div class="input-number-wrapper">
							<el-input
								controls-position="right"
								v-model="formData.expression.min"
								:max="formData.expression.type === 2 ? 36000 : 59"
								:min="0"
							></el-input>
							<span class="suffix" @blur="getExpressionLists">分</span>
						</div>
					</el-col>
					<el-col v-if="formData.expression.type == 8" :span="6">
						<div class="w-[300px]">
							<el-input
								v-model="formData.expression.cron"
								placeholder="请输入cron表达式，例如：1 2 * * *"
								:min="0"
								@blur="getExpressionLists"
							></el-input>
						</div>
					</el-col>
				</el-row>
				<el-row :gutter="12">
					<div class="trip w-[100%]">{{ expressionTrip }}</div>
					<div class="expression-table">
						<el-table :data="expressionLists" class="w-[300px]">
							<el-table-column prop="num" label="序号" min-width="80" />
							<el-table-column prop="date" label="执行时间" min-width="240" />
						</el-table>
					</div>
				</el-row>
			</el-form-item>
			<el-form-item label="参数：" prop="params">
				<div class="w-80">
					<el-input v-model="formData.params" placeholder="请输入参数，格式：--name admin" clearable />
				</div>
			</el-form-item>
			<el-form-item label="状态：">
				<el-switch v-model="formData.status" inline-prompt :active-value="1" :inactive-value="2" />
			</el-form-item>
			<el-form-item label="备注：" prop="remark">
				<div class="w-80">
					<el-input v-model="formData.remark" type="textarea" :autosize="{ minRows: 3, maxRows: 6 }" :maxlength="200" show-word-limit clearable />
				</div>
			</el-form-item>
		</el-form>
	</baseDialog>
</template>

<script setup lang="ts" name="crontabEdit">
import { ref, shallowRef, reactive, watch, computed } from 'vue';
import type { FormInstance } from 'element-plus';
import { crontabDetail, crontabAdd, crontabEdit, crontabExpression } from '/@/api/setting/crontab';

const dialogRef = ref(null);

const dialogType = ref('add');

const dialogTitle = computed(() => {
	return dialogType.value == 'add' ? '添加定时任务' : '编辑定时任务';
});

const emit = defineEmits(['submit', 'close']);

const formRef = shallowRef<FormInstance>();

const formData = reactive({
	id: 0,
	name: '',
	command: '',
	expression: {
		type: 1,
		min: 30,
		hour: 1,
		day: 1,
		week: 1,
		cron: '',
	},
	params: '',
	remark: '',
	status: 1,
});

const rules = reactive({
	name: [{ required: true, message: '请输入名称', trigger: ['blur'] }],
	command: [{ required: true, message: '请输入命令', trigger: ['blur'] }],
});

const typeList = [
	{
		name: '每天',
		value: 1,
	},
	{
		name: 'N天',
		value: 2,
	},
	{
		name: '每小时',
		value: 3,
	},
	{
		name: 'N小时',
		value: 4,
	},
	{
		name: 'N分钟',
		value: 5,
	},
	{
		name: '每星期',
		value: 6,
	},
	{
		name: '每月',
		value: 7,
	},
	{
		name: '自定义',
		value: 8,
	},
];

const weekList = [
	{ label: '周一', value: 1 },
	{ label: '周二', value: 2 },
	{ label: '周三', value: 3 },
	{ label: '周四', value: 4 },
	{ label: '周五', value: 5 },
	{ label: '周六', value: 6 },
	{ label: '周日', value: 7 },
];

const expressionTrip = ref('');

const expressionLists = ref([]);

watch(
	() => formData.expression,
	() => {
		switch (formData.expression.type) {
			case 1:
				expressionTrip.value = `每天${formData.expression.hour}时${formData.expression.min}分执行一次`;
				break;
			case 2:
				expressionTrip.value = `每${formData.expression.day}天的${formData.expression.hour}时${formData.expression.min}分执行一次`;
				break;
			case 3:
				expressionTrip.value = `每小时的${formData.expression.min}分执行一次`;
				break;
			case 4:
				expressionTrip.value = `每${formData.expression.hour}小时的${formData.expression.min}分执行一次`;
				break;
			case 5:
				expressionTrip.value = `每${formData.expression.min}分执行一次`;
				break;
			case 6:
				expressionTrip.value = `每星期${weekList[formData.expression.week - 1].label}的${formData.expression.hour}时${
					formData.expression.min
				}分执行一次`;
				break;
			case 7:
				expressionTrip.value = `每月${formData.expression.day}日的${formData.expression.hour}时${formData.expression.min}分执行一次`;
				break;
			case 8:
				expressionTrip.value = `自定义规则执行`;
				break;
		}
	},
	{
		immediate: true,
		deep: true,
	}
);

const handleSubmit = async () => {
	await formRef.value?.validate(async (valid: boolean) => {
		if (!valid) return;
		dialogType.value == 'add' ? await crontabAdd(formData) : await crontabEdit(formData);
		dialogRef.value?.close();
		emit('submit');
	});
};

const getExpressionLists = async (callback:any) => {
	let res = await crontabExpression({ expression: formData.expression });
	expressionLists.value = res;
	if(typeof callback === 'function')callback();
};

const setFormData = async (row: any, callback:any) => {
	const data = await crontabDetail({
		id: row.id,
	});

	for (const key in formData) {
		if (data[key] != null && data[key] != undefined) {
			formData[key] = data[key];
		}
	}

	callback();
};

const handleClose = () => {
	emit('close');
};

const open = (type = 'add') => {
	dialogType.value = type;
	// 初始化
	getExpressionLists(function(){
		dialogRef.value?.open();
	})
};

defineExpose({
	open,
	setFormData,
});
</script>

<style lang="scss">
.input-number-wrapper {
	position: relative;
	display: inline-block;
	width: 100%;
	vertical-align: middle;
	line-height: normal;

	.ivu-input-number {
		width: 100%;
		padding-right: 35px;
	}

	::v-deep .ivu-input-number-handler-wrap {
		right: 35px;
	}

	.suffix {
		position: absolute;
		top: 0;
		right: 0;
		z-index: 1;
		width: 35px;
		height: 100%;
		text-align: center;
		font-size: 12px;
		line-height: 33px;
		color: #333333;
	}
	.el-input__inner {
		padding-right: 50px;
	}
}

.trip {
	padding-left: 15px;
	color: #aaa;
}
</style>
